/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.oss.store.impl

import com.gitee.minimalismstyle.fresh.oss.api.model.OssFile
import com.gitee.minimalismstyle.fresh.oss.api.model.OssFileData
import com.gitee.minimalismstyle.fresh.oss.dao.OssFileDataDao
import com.gitee.minimalismstyle.fresh.oss.store.Store
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.InputStream
import java.io.OutputStream

/**
 * 数据库存储文件，支持分布式
 * @author maoxiaodong
 */
@Service
class DbStore(val ossFileDataDao: OssFileDataDao) : Store {

    @Transactional
    override fun write(ossFile: OssFile, inputStream: InputStream): String {
        val ossFileData = OssFileData()
        ossFileData.data = inputStream.readBytes()
        // 将二进制存入数据库
        ossFileDataDao.insert(ossFileData)
        return ossFileData.id.toString()
    }

    override fun read(ossFile: OssFile, os: OutputStream) {
        val ossFileData = ossFileDataDao.findById(ossFile.path?.toLong()!!)
        os.write(ossFileData.data)
    }

    override fun read(ossFile: OssFile): InputStream {
        val ossFileData = ossFileDataDao.findById(ossFile.path?.toLong()!!)
        return ossFileData.data!!.inputStream()
    }

    @Transactional
    override fun delete(path: String) {
        ossFileDataDao.deleteById(path.toLong())
    }
}